package com.lanou3g;

import java.io.*;

/**
 * Created by dllo on 18/4/20.
 */
public class NO3 {
    public static void main(String[] args) {
        String rootPath = "/Users/dllo/Desktop/hw/作业/Q2";
        String targetPath = "/Users/dllo/Desktop/hw/作业/Q3";
        File file = new File(rootPath);
        for (File file1 : file.listFiles()) {
            //mac文件夹中有隐藏文件，所以判断符合条件的文件
            if (file1.isFile() && file1.length() >=1024*1024*1024){
                split(file1,targetPath);
            }

        }
    }


    // 参数：拆的文件：拆完放哪－－－Q3
    public static void split(File file,String targetPath){

        //创建问价夹 ，与文件同名
        File targetDir = new File(targetPath,file.getName());

        targetDir.mkdirs(); //直接用..s就可以，能保证创建成功

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        int index = 0; //第几个文件

        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int pos = 0;
            byte[] buf = new byte[1024];
            File desFile = new File(targetDir,file.getName() + index);
            bos = new BufferedOutputStream(new FileOutputStream(desFile));
            long size =  0;
            while ((pos = bis.read(buf)) != -1){
                //写流
                bos.write(buf,0,pos);
                size += pos;
                //每写400兆 bos就指向新的文件

                if (size >= 400*1024*1024){
                    bos.close(); //把原来的流关掉
                    index ++; //下一个文件
                    size = 0; //大小重新统计
                    //bos 指向新的文件
                    bos = new BufferedOutputStream(new FileOutputStream(desFile));
                }
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }

    }


}
